import os
import cgi
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import memcache
import models

class Index(webapp.RequestHandler):
	def get(self):
		template_values = {"books":models.Book.all()}
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))
	def post(self):
		key_name = self.request.get('key_name')
		book = models.Book.get_by_key_name(key_name)
		if book:
			self.error(409)
		else:
			title = self.request.get('title')
			author = self.request.get('author')
			content = unicode(self.request.POST.get('content').file.read(), 'utf-8')
			book = models.Book(key_name=key_name, title=title, author=author, content=content)
			book.put()
			memcache.delete(key_name)
			self.redirect(book.url())

class Book(webapp.RequestHandler):
	def get(self, key_name):
		import rst
		book = models.Book.get_by_key_name(key_name)
		if book:
			import urllib
			url_param = urllib.urlencode({'chl': "http://libercoli.appspot.com/"+key_name})
			html_body = memcache.get(key_name)
			if html_body is None:
				html_body = rst.rst2html(book.content)
				memcache.add(key_name, html_body)
			path = os.path.join(os.path.dirname(__file__), 'book.html')
			self.response.out.write(template.render(path, {'book': book, 'body': html_body, 'url_param': url_param}))
		else:
			self.error(404)

class RawBook(webapp.RequestHandler):
	def get(self, key_name):
		book = models.Book.get_by_key_name(key_name)
		if book:
			self.response.headers['Content-Type'] = 'text/x-rst'
			self.response.out.write(book.content)
		else:
			self.error(404)

application = webapp.WSGIApplication([
	('/', Index),
	('/raw/(.*)', RawBook),
	('/(.*)', Book),
	], debug=True)

if __name__ == "__main__":
	run_wsgi_app(application)
